package com.slkj.shilixiaoyuanapp.ui.teacher.tool.homework;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.slkj.shilixiaoyuanapp.BuildConfig;
import com.slkj.shilixiaoyuanapp.R;
import com.slkj.shilixiaoyuanapp.base.ActivityInfo;
import com.slkj.shilixiaoyuanapp.base.BaseActivity;
import com.slkj.shilixiaoyuanapp.entity.HomeWorkInfoEntity;
import com.slkj.shilixiaoyuanapp.entity.KnowledgeAllEntity;
import com.slkj.shilixiaoyuanapp.entity.code.UiCode;
import com.slkj.shilixiaoyuanapp.net.callback.BaseFunctionCallBack;
import com.slkj.shilixiaoyuanapp.net.CommonResult;
import com.slkj.shilixiaoyuanapp.net.HttpHeper;
import com.slkj.shilixiaoyuanapp.net.callback.CommonCallBack;
import com.slkj.shilixiaoyuanapp.ui.common.adapter.ChosePicAdapter;
import com.slkj.shilixiaoyuanapp.util.TimeUtils;
import com.slkj.shilixiaoyuanapp.util.UpdataFileUtil;
import com.slkj.shilixiaoyuanapp.util.picture.FileUtils;
import com.slkj.shilixiaoyuanapp.util.picture.TakePictureUtils;
import com.slkj.shilixiaoyuanapp.view.DialogProvider;
import com.slkj.shilixiaoyuanapp.view.NumberEditText;
import com.slkj.shilixiaoyuanapp.view.PickerViewProvider;
import com.slkj.shilixiaoyuanapp.view.choosedialog.ChooseDialog;
import com.slkj.shilixiaoyuanapp.view.dialog.LoadSuccessAndFailDialog;
import com.tkk.api.RxEventProcessor;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.ObservableSource;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.CHOSE_PIC_MAX_SIZW;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.CHOSE_PIC_SPAN_COUNT;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.NO_CHOSE;

@RuntimePermissions
@ActivityInfo(layout = R.layout.activity_assignment, title = "布置作业", rightHint = "历史记录")
public class AssignmentActivity extends BaseActivity implements ChooseDialog.OnSureClickListener<HomeWorkInfoEntity.GradeEntity> {
    @BindView(R.id.tv_obj)
    TextView tvObj;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_km)
    TextView tvKm;
    @BindView(R.id.tv_work_type)
    TextView tvWorkType;
    @BindView(R.id.tv_point)
    TextView tvPoint;
    @BindView(R.id.recyc_pic)
    RecyclerView recycerPic;
    @BindView(R.id.edit_content)
    NumberEditText editContent;
    ArrayList<String> picPaths = new ArrayList<>();
    ChosePicAdapter adapter;
    public TakePictureUtils takePictureUtils;
    HomeWorkInfoEntity infos;
    OptionsPickerView pickerKmView;
    OptionsPickerView pickerWorkTypeView;
    OptionsPickerView pickerKnowledgeView;
    String time;
    List<Integer> objIds = new LinkedList<>();
    int subjectId = NO_CHOSE;
    int homeWorkTypeId = NO_CHOSE;
    int knowledgeId = NO_CHOSE;
    //选择班级dialog
    ChooseDialog<HomeWorkInfoEntity.GradeEntity> choseObjDialog;
    /**
     * 知识点数据
     */
    List<KnowledgeAllEntity.KnowledgeEntity> knowledgeEntityList = new ArrayList<>();

    @Override
    protected void init() {
        RxEventProcessor.get().bind(this);
        recycerPic.setLayoutManager(new GridLayoutManager(this, CHOSE_PIC_SPAN_COUNT));
        adapter = new ChosePicAdapter(picPaths, this);
        recycerPic.setAdapter(adapter);
        takePictureUtils = TakePictureUtils.Builder.from(this).isCompressor(false).isTailor(false).creat();
        takePictureUtils.setTakeCallBacklistener(new TakePictureUtils.TakePictureListener() {
            @Override
            public void successful(File outFile) {
                picPaths.add(outFile.getPath());
                adapter.notifyItemInserted(picPaths.size());
            }
            @Override
            public void failed(int errorCode, List<String> deniedPermissions) {
            }
        });

    }

    @Override
    protected void onRightTitleClick() {
        startActivity(WorkHistoryListActivity.class);
    }


    @OnClick(R.id.layout_chose_obj)
    void choseObj() {
        if (infos == null) {
            getHomeWorkInfos(1);
        } else {
            choseObjDialog.show();
        }
    }

    @OnClick(R.id.layout_chose_km)
    void choseKm() {
        if (infos == null) {
            getHomeWorkInfos(2);
        } else {
            pickerKmView.show();
        }

    }


    @OnClick(R.id.layout_chose_work_type)
    void choseWorkType() {
        if (infos == null) {
            getHomeWorkInfos(3);
        } else {
            pickerWorkTypeView.show();
        }
    }

    /**
     * 获取发布对象1，+作业类型 3+ 科目2
     */
    private void getHomeWorkInfos(int type) {
        HttpHeper.get().toolService().getHomeWorkInfos().compose(bindToLifecycle()).compose(getThread())
                .subscribe(new CommonCallBack<HomeWorkInfoEntity>(true,this) {
                    @Override
                    public void onCallBackSuccess(HomeWorkInfoEntity data) {
                        infos = data;
                        choseObjDialog = new ChooseDialog<>(AssignmentActivity.this, infos.getGrade());
                        choseObjDialog.setListener(AssignmentActivity.this);
                        pickerKmView = PickerViewProvider.getCommonPicker(AssignmentActivity.this, data.getSubject(), (options1, options2, options3, v) -> {
                            //科目改变
                            if (subjectId != NO_CHOSE && subjectId != data.getSubject().get(options1).getId()){
                                clearPoint();
                            }
                            tvKm.setText(data.getSubject().get(options1).getName());
                            subjectId = data.getSubject().get(options1).getId();
                        });
                        pickerWorkTypeView = PickerViewProvider.getCommonPicker(AssignmentActivity.this, data.getHomeworkType(), (options1, options2, options3, v) -> {
                            tvWorkType.setText(data.getHomeworkType().get(options1).getName());
                            homeWorkTypeId = data.getHomeworkType().get(options1).getId();
                        });
                        if (type == 1) {
                            choseObjDialog.show();
                        } else if (type == 2) {
                            pickerKmView.show();
                        } else if (type == 3) {
                            pickerWorkTypeView.show();
                        }
                    }
                });
    }

    /**
     * 选择发布对象成功
     *
     * 判断是否同一个年级-去重-判断size
     */
    @Override
    public void onSureClick(List<HomeWorkInfoEntity.GradeEntity> list) {
        if (list.isEmpty()){
            objIds.clear();
            clearPoint();
        }
        else {
            LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
            for (HomeWorkInfoEntity.GradeEntity gradeEntity : list) {
                set.add(gradeEntity.getYear());
                objIds.add(gradeEntity.getCId());
            }
            if (set.size() > 1) {
                showToast("只能同时选择一直年级");
                objIds.clear();
                return;
            }
            //发布对象改变
            if (!objIds.isEmpty() && !objIds.get(0).equals(list.get(0).getCId())){
                clearPoint();
            }
            String infos = "";
            switch (list.size()) {
                case 1:
                    infos = list.get(0).getClassName();
                    break;
                case 2:
                    infos = list.get(0).getClassName() + "," + list.get(1).getClassName();
                    break;
                default:
                    infos = list.get(0).getClassName() + "," + list.get(1).getClassName() + "等" + list.size() + "班级";
                    break;
            }
            tvObj.setText(infos);
        }
    }

    /**
     * 清空知识点
     */
    void  clearPoint(){
        knowledgeId = NO_CHOSE;
        tvPoint.setText("");
        knowledgeEntityList.clear();

    }

    /**
     * 选择知识点-必须先选择科目和班级
     */
    @OnClick(R.id.layout_chose_point)
    void chosePoint() {
        if (subjectId == -1 || objIds.size() == 0) {
            showToast("请先选择科目和发布对象");
            return;
        }
        if (knowledgeEntityList.isEmpty()) {
            HttpHeper.get().toolService()
                    .getKnowledge(objIds.get(0), subjectId)
                    .compose(bindToLifecycle())
                    .compose(getThread())
                    .subscribe(new CommonCallBack<List<KnowledgeAllEntity>>(true, this) {
                        @Override
                        public void onCallBackSuccess(List<KnowledgeAllEntity> data) {
                            for (KnowledgeAllEntity knowledgeAllEntity : data) {
                                knowledgeEntityList.addAll(knowledgeAllEntity.getKnowledge());
                            }
                            pickerKnowledgeView = PickerViewProvider.getCommonPicker(AssignmentActivity.this, knowledgeEntityList, (options1, options2, options3, v) -> {
                                tvPoint.setText(knowledgeEntityList.get(options1).getKName());
                                knowledgeId = knowledgeEntityList.get(options1).getKId();
                            });
                            pickerKnowledgeView.show();
                        }
                    });
        }else {
            pickerKnowledgeView = PickerViewProvider.getCommonPicker(AssignmentActivity.this, knowledgeEntityList, (options1, options2, options3, v) -> {
                tvPoint.setText(knowledgeEntityList.get(options1).getKName());
                knowledgeId = knowledgeEntityList.get(options1).getKId();
            });
            pickerKnowledgeView.show();
        }


    }


    @OnClick(R.id.layout_chose_time)
    void choseTime() {
        PickerViewProvider.getAfterTimePicker(this, (date, v) -> {
            time = TimeUtils.dateToStrM(date);
            tvTime.setText(time);
        }).show();
    }

    @OnClick(R.id.layout_chose_pic)
    void chosePic() {
        if (picPaths.size() == CHOSE_PIC_MAX_SIZW) {
            showToast("最多添加" + CHOSE_PIC_MAX_SIZW + "张图片");
            return;
        }
        DialogProvider.getPhotoDialog(this, new DialogProvider.TakePicTypeListener() {
            @Override
            public void takePhoto() {
                takePictureUtils.getByCarema();
            }

            @Override
            public void chosePhoto() {
                AssignmentActivityPermissionsDispatcher.onAgreePermissionWithPermissionCheck(AssignmentActivity.this);
            }
        });

    }

    /**
     * 上传数据
     */
    @OnClick(R.id.tv_up)
    void upData() {

        if (objIds.isEmpty()) {
            LoadSuccessAndFailDialog.showFail(this,"请选择发布对象");

            return;
        }
        if (TextUtils.isEmpty(time)) {
            LoadSuccessAndFailDialog.showFail(this,"请选择截止时间");

            return;
        }
        if (subjectId == NO_CHOSE) {
            showToast("请选择科目");
            return;
        }
        if (homeWorkTypeId == NO_CHOSE) {
            showToast("请选择作业类型");
            return;
        }
        String content = editContent.getText();

        if (knowledgeId == NO_CHOSE) {
            showToast("请选择知识点");
            return;
        }

        UpdataFileUtil.UpImgObservable("homework", picPaths)
                .flatMap(new BaseFunctionCallBack<List<String>, String>() {
                    @Override
                    public ObservableSource<CommonResult<String>> back(List<String> result) {
                        String img = com.slkj.shilixiaoyuanapp.util.StringUtils.listToString(result);
                        return HttpHeper.get().toolService().sendHomeWork(objIds.toString(), subjectId, homeWorkTypeId, content, time, knowledgeId, img);
                    }
                })
                .compose(getThread())
                .compose(bindToLifecycle())
                .subscribe(new CommonCallBack<String>(true,AssignmentActivity.this) {
                    @Override
                    public void onCallBackSuccess(String data) {
                        LoadSuccessAndFailDialog.showSuccess(AssignmentActivity.this,data);
                        clearContent();
                    }
                });


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxEventProcessor.get().unBind(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        takePictureUtils.attachToActivityForResult(requestCode, resultCode, data);
        if (requestCode == UiCode.CHOSE_PIC_CODE && resultCode == RESULT_OK) {
            List<Uri> mSelected = Matisse.obtainResult(data);
            for (int i = 0; i < mSelected.size(); i++) {
                String filePath = FileUtils.getPathByUri(this, mSelected.get(i));
                picPaths.add(filePath);
            }
            adapter.notifyItemRangeInserted(picPaths.size(), mSelected.size());
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        takePictureUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AssignmentActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onAgreePermission() {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(true)
                .maxSelectable(CHOSE_PIC_MAX_SIZW - picPaths.size())
                .captureStrategy(new CaptureStrategy(true, BuildConfig.APPLICATION_ID + ".fileprovider"))
                .imageEngine(new GlideEngine())
                .forResult(UiCode.CHOSE_PIC_CODE);
    }

    @OnPermissionDenied({Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE})
    void onDeniedPermission() {
        showToast("读取照片权限获取失败");
    }
}
